package com.readytheory.thisisstupid;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;


public class SayingIO {
    private static final String PERSISTENCE_UNIT_NAME = "Saying";
    private static EntityManagerFactory factory;

    public void Add(String sayingtext, String author) {
	if( sayingtext == null )
	    return ;
	if(sayingtext.trim().length() < 8 )
	    return ;
	factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	Saying saying = new Saying();
	saying.setAuthorname(author);
	saying.setText(sayingtext);
	em.persist(saying);
	em.getTransaction().commit();
    }

    public String getAll() {
	factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	EntityManager em = factory.createEntityManager();
	Query q = em.createQuery("Select x from Saying x");
	List<Saying> results = q.getResultList();

	String retval = "";
	for(Saying s : results) {
	    retval += s.getText() ;
	    retval += "\n" ;
	}
	return retval ;
    }
}

		
	